from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from alipay import AliPay
from django.conf import settings
import os

from orders.models import OrderInfo
from .models import Payment
# Create your views here.


# payment/status/?支付宝参数
class PaymentStatusView(APIView):
    """修改订单的状态"""
    # ?charset=utf-8&out_trade_no=20180707065708000000001&method=alipay.trade.page.pay.return&total_amount=11374.00&sign=IZbYpOSz6rc0FPg7ADRzubyG2GPyqXN%2BDTQj0vv58uulQoNIdTCE%2BOxG%2FgUj46xc3kfpDnfGQPX8ovBCzruWnOIzhcnH5p1vU7x8ngi2rKOIC09mw1Us6RD17aFth8sGKGfRni%2Fs9ZLTEQpI8dZLaGpuJZ%2BlGNZFPyaSzab5WyHgXVE%2FimLfZW66xnkErpWdUroaMzkGcNGYGFdMYszJS8gG9fCjj849waEsGvnaIkt%2FN5LQrnc60uiyP2imxWqZrQoxgOyoNJBx7V9C5FhmT1jPEikf7q19X3FOtB9gwsbjglUL3Rvy7MvvDBW5PVbae4XbT47YcJN4xWBdbo4u8w%3D%3D&trade_no=2018070721001004510200538669&auth_app_id=2016082100308405&version=1.0&app_id=2016082100308405&sign_type=RSA2&seller_id=2088102172481561&timestamp=2018-07-07+16%3A37%3A51
    def put(self, request):
        # 读取？后面的查询字符串
        # QueryDict类型的数据，不是标准的python字典
        # 存储一键一值，一键多值。get(). getlist()
        query_dict = request.query_params
        data = query_dict.dict() # 将QueryDict类型的数据强转为python标准字典
        signature = data.pop("sign")

        # 创建对接支付宝的SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        # 使用data进过RSA2计算，得到结果跟signature比较，如果为True，表示支付成功
        success = alipay.verify(data, signature)
        if success:
            # 读取支付宝维护的交易流水号和美多商城维护的订单编号
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')

            # 记录支付宝维护的交易流水号
            Payment.objects.create(
                order_id=order_id,
                trade_id = trade_id
            )

            # 修改订单的状态为代发货
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM["UNSEND"])

            return Response({'trade_id':trade_id})
        else:
            return Response({'message':'非法请求'}, status=status.HTTP_403_FORBIDDEN)


# orders/(?P<order_id>\d+)/payment/
class PaymentView(APIView):
    """对接支付宝的支付"""

    # 必须登录用户才能访问
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):
        # 获取order_id,校验order_id
        # 查询order

        try:
            order = OrderInfo.objects.get(order_id=order_id, user=request.user, pay_method=OrderInfo.PAY_METHODS_ENUM["ALIPAY"],
                                          status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"])
        except OrderInfo.DoesNotExist:
            return Response({'message':'非法请求'}, status=status.HTTP_400_BAD_REQUEST)

        # 创建对接支付宝的SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        # 调用对接支付宝的支付接口
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url="http://www.meiduo.site:8080/pay_success.html",
        )

        # 正式环境：电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        # 测试环境：电脑网站支付，需要跳转到https://openapi.alipaydev.com/gateway.do? + order_string
        # 响应alipay_url
        alipay_url = settings.ALIPAY_URL + '?' + order_string
        return Response({'alipay_url':alipay_url})
